//流程引擎工具条
<template>
    <vp-btn ref="startBtnRef" :loading="loading" @click="handleNew" v-if="!processInsId" type="info" ><vp-label zh="发起流程" en="Start Process"></vp-label></vp-btn>
    <vp-btn ref="agreeBtnRef" :loading="loading" @click="handleAgree" v-if="processInsId" type="primary" ><vp-label zh="同意" en="Agree"></vp-label></vp-btn>
    <vp-btn ref="rejectBtnRef" :loading="loading" @click="handleReject" v-if="processInsId && showReject" type="danger"><vp-label zh="驳回" en="Reject"></vp-label></vp-btn>
    <vp-btn ref="transferBtnRef" :loading="loading" @click="handleTransfer" v-if="processInsId && showTransfer"><vp-label zh="转办" en="Transfer"></vp-label></vp-btn>
    <vp-btn ref="delegateBtnRef" :loading="loading" @click="handleDelegate" v-if="processInsId && showDelegate"><vp-label zh="委派/加签" en="Delegate"></vp-label></vp-btn>
    <vp-btn ref="stopBtnRef" :loading="loading" @click="handleStop" v-if="processInsId && showCancel" type="danger"><vp-label zh="中止" en="Stop"></vp-label></vp-btn>
    <el-popover
        ref="popoverRef"
        :virtual-ref="buttonRef"
        title="流程处理 Process Handle"
        virtual-triggering
        :visible="popoverVisible"
        width="50%"
    >
        <div class="clickDiv" v-click-outside="onClickOutside">
            <el-form label-suffix=":" v-loading="loading"  :model="formData" :rules="formRules" ref="formRef" :label-width="labelWidth">
                <el-form-item v-if="formData.operate === 'completed'" :label="$t('workflow.priority')" prop="priority">
                    <template #label><vp-label zh="优先级" en="Priority" align="left"/></template>
                    <el-radio-group size="small" v-model="formData.priority" class="w100">
                        <!-- <el-radio-button :label="10">{{ $t('workflow.priority10') }}</el-radio-button> -->
                        <el-radio-button :label="20"><vp-label  zh="紧急" en="Urgent"/></el-radio-button>
                        <el-radio-button :label="30"><vp-label zh="急" en="High"/></el-radio-button>
                        <el-radio-button :label="40"><vp-label zh="一般" en="Normal"/></el-radio-button>
                        <!-- <el-radio-button :label="50">{{ $t('workflow.priority50') }}</el-radio-button> -->
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-if="formData.operate === 'reject'" :label="$t('workflow.task.nextStep')" prop="nextStep">
                    <template #label><vp-label zh="驳回到" en="Next Step" align="left"/></template>
                    <el-select v-model="formData.nextStep" placeholder="Select" append-to=".clickDiv">
                        <el-option
                            v-for="item in filterNextSteps"
                            :key="item.id"
                            :label="item.activityName"
                            :value="item.activityId"
                        >
                        </el-option>
                    </el-select>    
                </el-form-item>
                <el-form-item v-if="formData.operate === 'transfer' || formData.operate === 'delegate'" :label="$t(`workflow.task.operate.${formData.operate}`)" prop="nextUserId">
                    <template #label>
                        <vp-label v-if="formData.operate === 'transfer'" zh="转办" en="Transfer" align="left"/>
                        <vp-label v-if="formData.operate === 'delegate'" zh="委派/沟通" en="Delegate" align="left"/>
                    </template>
                    <VpUserSelect append-to=".clickDiv"
                        :selectedId="formData.nextUserId"
                        @userSelected="userSelected"
                        class="w100"
                    ></VpUserSelect>
                </el-form-item>
                <slot v-if="formData.operate === 'completed'"></slot>
                <el-form-item :label="$t('item.comments')" prop="comments" :rules="(formData.operate === 'reject' || formData.operate === 'cancel')?[ validateUtils.notNull, ]:[]">
                    <template #label><vp-label zh="说明" en="Comments" align="left"/></template>
                    <el-input type="textarea" v-model="formData.comments" maxlength="1000">
                    </el-input>
                </el-form-item>
                <el-form-item :label="$t('item.attachment')" prop="attachments">
                    <template #label><vp-label zh="附件" en="Attachment" align="left"/></template>
                    <VpRowAttachment class="w100" v-model:attachmentList="formData.attachments" @attachmentListEmit="getAttachmentListEmit($event,formData)"></VpRowAttachment>
                </el-form-item>
                <el-row>
                    <div style=" width:100%; text-align: center;">
                        <vp-btn-cancel @click="handleClose"/>
                        <vp-btn-confirm @click="handleConfirm"/>
                    </div>
                </el-row>
            </el-form> 
        </div>    
    </el-popover>
</template>
<script setup lang="ts" name="VpProcessToolBar">
import { computed, onMounted, ref, unref } from 'vue';
import { ElMessage, ClickOutside as vClickOutside} from 'element-plus';
import validateUtils from '/@/utils/validateUtils';
import request from '/@/utils/request';
import mittBus from '/@/utils/mitt';
import { useRoute } from 'vue-router';
import VpUserSelect from "/@/components/vp/user/VpUserSelect.vue";
import VpRowAttachment from '/@/components/vp/file/VpRowAttachment.vue';

const route = useRoute();

    const props = withDefaults(defineProps<{
        processInsId?: string,
        taskId?: string,
        labelWidth?: string,
        showCancel?: boolean,
        showReject?: boolean,
        showTransfer?: boolean,
        showDelegate?: boolean,
        showComments?:boolean,
        rejectLastNode?:boolean,
        beforeShowFn?: Function,
        beforeAgreeFn?: Function,
        afterAgreeFn?: Function,
        afterCancelFn?: Function,
        loading?: boolean,
        setLoadingFn?: Function,
    }>(), {
        labelWidth: '120px',
        showCancel: false,
        showReject: true,
        showTransfer: true,
        showDelegate: true,
        showComments: true,
        rejectLastNode: false,
        beforeShowFn: (): Promise<any> => { return Promise.resolve();},
        beforeAgreeFn: (): Promise<any> => { return Promise.resolve();},
        afterAgreeFn: (): Promise<any> => { return Promise.resolve();},
        afterCancelFn: (): Promise<any> => { return Promise.resolve();},
        loading: false,
        setLoadingFn: (loading: boolean)=>{},
    });

    const formData = ref({
        priority: 40,
        comments: "",
        operate: "completed",
        nextStep: "",
        nextUserId: "",
        attachments: [],
    });

    const formRules = {
        operate:[
            validateUtils.notNull,
        ],
        nextUserId:[
            validateUtils.notNull,
        ],
    }

    const getAttachmentListEmit = (data: any, row: any)=>{
        row.attachments = data;
    }

    //可驳回的节点
    const nextSteps = ref([]);

    onMounted(()=>{
        if(props.processInsId && props.taskId){
            request.get(`/workflow/process/finished/${props.processInsId}/${props.taskId}`).then((res)=>{
                nextSteps.value = res?.data || [];
                if(nextSteps.value && nextSteps.value.length > 0){
                    formData.value.nextStep = filterNextSteps.value[0].activityId;
                }
            })
        }
    })

    const filterNextSteps = computed(() => {
        // 仅可驳回至上一节点
        if (props.rejectLastNode && nextSteps.value.length > 0) {
            return nextSteps.value.slice(nextSteps.value.length - 1);
        }
        return nextSteps.value;
    })

    const userSelected = (item: any) => {
        formData.value.nextUserId = item.id;
    }

    const buttonRef = ref();
    const startBtnRef = ref();
    const popoverRef = ref();
    const popoverVisible = ref(false);

    //显示流程处理窗口
    const showPopover = (el:any) => {
        buttonRef.value = el.currentTarget;
        popoverVisible.value = true;
    }

    const onClickOutside = () => {
        if(popoverVisible.value){
            popoverVisible.value= false;
        }
    }

    //点击发起流程按钮
    const handleNew = (el:any) => { 
        props.beforeShowFn().then(()=>{
            formData.value.operate = "completed";
            showPopover(el);
        });
    }
    //点击同意按钮
    const handleAgree = (el:any) => { 
        props.beforeShowFn().then(()=>{
            formData.value.operate = "completed";
            showPopover(el);
        });
    }
    //点击驳回按钮
    const handleReject = (el:any) => { 
        formData.value.operate = "reject";
        showPopover(el);
    }
    //点击转办按钮
    const handleTransfer = (el:any) => { 
        formData.value.operate = "transfer";
        showPopover(el);
    }
    //点击委派按钮
    const handleDelegate = (el:any) => { 
        formData.value.operate = "delegate";
        showPopover(el);
    }
    //点击中止按钮
    const handleStop = (el:any) => { 
        formData.value.operate = "cancel";
        showPopover(el);
    }
    //popover取消按钮
    const handleClose = () => { 
        popoverVisible.value= false;
    }

    const formRef = ref();
    //确定按钮
    const handleConfirm = () => {
        if(formData.value.operate === "completed" ){
            props.beforeAgreeFn().then(()=>{
                formRef.value.validate((valid: boolean) => {
                    if (valid) {
                        props.afterAgreeFn({
                            ...formData.value,
                            taskId: props.taskId,
                            processInsId: props.processInsId,
                        })
                        popoverVisible.value= false;
                    }
                })
            });
        }else if(formData.value.operate === "reject" || formData.value.operate === "transfer" || formData.value.operate === "delegate"){
            formRef.value.validate((valid: boolean) => {
                if (valid) {
                    props.setLoadingFn(true);
                    request.post("/workflow/task/complete", {
                        ...formData.value,
                        taskId: props.taskId,
                        processInsId: props.processInsId,
                    }).then(()=>{ 
                        mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
                        ElMessage.success("操作成功/Operation Succeeded");
                    }).finally(()=>{
                        props.setLoadingFn(false);
                    })
                }
            })
        }else if(formData.value.operate === "cancel" ){
            formRef.value.validate((valid: boolean) => {
                if (valid) {
                    popoverVisible.value= false;
                    props.afterCancelFn({
                        ...formData.value,
                        taskId: props.taskId,
                        processInsId: props.processInsId,
                    })
                }
            })
        }
    }



</script>
<style scoped lang="scss">

</style>